package com.example.controller;



import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.domain.User;
import com.example.domain.paging.PageHelper;
import com.example.service.IUserService;
import com.example.domain.edit.NewPassword;
import com.example.domain.query.UserQuery;
import com.example.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2024-04-17
 */
@Api(tags = "用户管理接口")
@RestController
@RequestMapping("/user")
@PreAuthorize("hasAnyAuthority('admin')")
@Slf4j
public class UserController {
    @Autowired
    private IUserService userService;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    boolean flag0=true;
    @PostMapping("/loginSuccess")
    @ResponseBody
    public String loginSuccess(){
        return "hello!";
    }
    //增加
    @ApiOperation("添加用户接口")
    @PostMapping
    public Result save(@RequestBody User user){
        boolean flag = userService.save(user);
        return new Result(flag,flag? "添加成功^_^!" : "添加失败~_~!");
    }

    //查询所有
    @ApiOperation("查询所有用户接口")
    @GetMapping
    public Result getAll() {
        String getAll = "getAll"; // 设置缓存键
        // 先从缓存中获取数据
        List<User> userList = (List<User>) redisTemplate.opsForValue().get(getAll);
        if (userList == null) {
            // 缓存中没有数据，则从数据库中获取数据
            userList = userService.list();
            // 将数据存入缓存
            redisTemplate.opsForValue().set(getAll, userList);
        }
        boolean  flag = userList != null ? flag0 : !flag0;
        return new Result(flag, userList,flag? "查询成功^_^!" : "查询失败~_~!");
    }
    //根据id进行查询
    @ApiOperation("根据用户id查询接口")
    @GetMapping("{id}")
    public Result getById(@PathVariable Integer id){
        User user = userService.getById(id);
        boolean  flag = user != null ? flag0 : !flag0;
        return new Result(flag,user,flag? "查询成功^_^!" : "查询失败~_~!");
    }

    //修改
    @ApiOperation("根据用户id修改接口")
    @PutMapping
    public Result update(@RequestBody User user){
        boolean flag = userService.modify(user);
        return new Result(flag,userService.modify(user),flag? "修改成功^_^!" : "修改失败~_~!");
    }

    //删除
    @ApiOperation("根据用户id删除接口")
    @DeleteMapping("{id}")
    public Result delete(@PathVariable Integer id){
        boolean flag = userService.delete(id);
        return new Result(flag,userService.delete(id),flag? "删除成功^_^!" : "删除失败~_~!");
    }

    //分页查询
    @ApiOperation("分页查询接口")
    @GetMapping("{currentPage}/{pageSize}")
    public Result getPage(@PathVariable Integer currentPage,@PathVariable Integer pageSize, User user){
        IPage<User> page = userService.getPage(currentPage, pageSize,user);
        //如果当前页码值大于了总页码值，那么重新执行查询操作，使用最大页码值作为当前页码值
        if (currentPage > page.getPages()){
            page=userService.getPage( (int)page.getPages(), pageSize,user);
        }
        boolean  flag = page != null ? flag0 : !flag0;
        return new Result(flag,page,flag? "查询成功^_^!" : "查询失败~_~!");
    }

    //条件查询
    @ApiOperation("条件查询接口")
    @GetMapping("/query")
    public Result queryUsers(@RequestBody UserQuery userQuery){
        Result result = new Result();
        if (userQuery != null){
            int page=(userQuery.getCurrentPage()-1)*userQuery.getPageSize();
            userQuery.setCurrentPage(page);
        }
        List<User> all=userService.queryUsers(userQuery.getUsername(),userQuery.getPhone(),userQuery.getStatus());
        List<User> count = userService.list();
        if (all !=null){
            result.setFlag(true);
            result.setMsg("查询成功^_^!");
            result.setData(all);
            result.setTotal(count.size());
        }else {
            result.setFlag(false);
            result.setMsg("查询失败~_~!");
        }
        return result;
    }

    //修改密码
    @ApiOperation("修改密码")
    @PostMapping("/editPassword")
    @PreAuthorize("hasAnyAuthority('admin','supplier','buyer')")
    public Result editPassword(@RequestBody NewPassword newPassword){
        Result result = new Result();
        if (newPassword !=null){
            User userByUid = userService.getById(newPassword.getUid());
            if (newPassword.getOldPassword().equals(userByUid.getPassword())){
                int i = userService.editPassword(newPassword);
                if (i>0){
                    result.setFlag(true);
                    result.setMsg( "密码修改成功^_^!");
                    return result;
                }
            }
        }
        result.setFlag(false);
        result.setMsg("密码修改失败~_~!");
        return result;
    }
    @ApiOperation("分页查询")
    @GetMapping("list")
    public Result findAll(@RequestBody PageHelper pageHelper){
        Result result = new Result();
        if (pageHelper !=null){
            int page= (pageHelper.getCurrentPage()-1)*pageHelper.getPageSize();
            pageHelper.setCurrentPage(page);
        }
        List<User> all = userService.findAll(pageHelper);
        List<User> count = userService.list();
        if (all !=null){
            result.setFlag(true);
            result.setMsg("查询成功^_^!");
            result.setData(all);
            result.setTotal(count.size());
        }else {
            result.setFlag(false);
            result.setMsg("查询失败~_~!");
        }
        return result;
    }

}
